# coding=utf-8
from urlparse import urlparse

from django.core.urlresolvers import reverse
from django.core.exceptions import ObjectDoesNotExist

from common.config import hot_task_config
from task.models import TaskBase
from models import HeatTask


class HeatTaskCountMiddleware(object):
    """
    根据客户端的请求，计算热门任务
    """

    @staticmethod
    def process_request(request):
        path = urlparse(request.get_full_path())
        if path.path not in [reverse('task_detail'), reverse('join_task')]:
            return None
        # todo 统计任务查看、参入次数，计算任务热度，放入消息队列中进行操作
        reset = path.query.find('=')
        if reset is not -1:
            task_id = path.query[reset + 1:]
        else:
            task_id = request.POST.get('id', 0)
        print task_id
        task_base = TaskBase.objects.get(pk=task_id)

        try:
            heat_task = HeatTask.objects.get(task_base=task_id)
            if path.path == reverse('task_detail'):
                heat_task.heat_point = heat_task.heat_point + hot_task_config.get('detail')
                heat_task.look_num = heat_task.look_num + 1
            elif path.path == reverse('join_task'):
                heat_task.heat_point = heat_task.heat_point + hot_task_config.get('join')
                heat_task.join_num = heat_task.join_num + 1
            heat_task.save()
        except ObjectDoesNotExist:
            heat_task = HeatTask(
                task_base=task_base,
                heat_point=hot_task_config.get('detail'),
                look_num=1
            )
            heat_task.save()
        return None

